package com.group.project.hrms.filter;
import com.auth0.jwt.interfaces.Claim;
import com.group.project.hrms.utils.JwtUtilForHRMS;
import lombok.extern.slf4j.Slf4j;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import javax.servlet.*;
import javax.servlet.annotation.WebFilter;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.Map;

/**
 * 该类是JWT过滤器，拦截 /hrms/*的请求
 */
@Slf4j
@WebFilter(filterName = "WebFilterForHRMS", urlPatterns = {"/hrms/*", "/basic/*"})
public class WebFilterForHRMS implements Filter {
    private static Logger logger = LoggerFactory.getLogger(WebFilterForHRMS.class);

    @Override
    public void init(FilterConfig filterConfig) throws ServletException {
    }

    @Override
    public void doFilter(ServletRequest req, ServletResponse res, FilterChain chain) throws IOException, ServletException {
        final HttpServletRequest request = (HttpServletRequest) req;
        final HttpServletResponse response = (HttpServletResponse) res;
        logger.info(request.getRemoteAddr() + " is trying to cross WebFilter ... ");
        response.setCharacterEncoding("UTF-8");
        //获取 header里的token
        final String token = request.getHeader("authorization");

        if ("OPTIONS".equals(request.getMethod())) {
            response.setStatus(HttpServletResponse.SC_OK);
            chain.doFilter(request, response);
        }
        //Except OPTIONS, other request should be checked by JWT
        else {
            if (token == null) {
                response.getWriter().write("A");//no token!
                logger.info("no token!");
                return;
            }
            Map<String, Claim> userData = JwtUtilForHRMS.verifyToken(token);
            if (userData == null) {
                response.getWriter().write("B");//token is wrong!
                logger.info("token is wrong!");
                return;
            }
            String id = userData.get("staffDingId").asString();
            String name = userData.get("staffName").asString();
            String contactId = userData.get("contactId").asString();

            //拦截器 拿到用户信息，放到request中
            request.setAttribute("staffDingId", id);
            request.setAttribute("staffName", name);
            request.setAttribute("contactId", contactId);
            logger.info("token pass!");
            chain.doFilter(req, res);
        }
    }

    @Override
    public void destroy() {
    }
}
